'use strict';

const { Controller } = require('egg');
const { parseStringXml } = require('../util/common');

class BasicMessageController extends Controller {
  async replyMessage() {
    const { ctx } = this;
    const xml = this.ctx.request.body;
    try {
      const {
        createTime, msgType, toUserName, toFromName, event, msgContent,
      } = await parseStringXml(xml);
      const dataPool = [
        {
          msgContent: '你好，您好，嗨',
          reply_msg: '您好，请问有什么需要帮您的？☺☺☺'
        },
        {
          msgContent: '歌曲推荐',
          reply_msg: '上QQ音乐，找到你喜欢的歌曲，https://y.qq.com/'
        }
      ];
      const replyResultFilter = dataPool.filter(item => item.msgContent.includes(msgContent));
      const replyResult = replyResultFilter.length !== 0 ? replyResultFilter[0] : {
        msgContent: 'No Msg',
        reply_msg: '你说的我听不懂，请详细描述一下你的问题！😭'
      };
      let body = '';
      if (msgType === 'event' && event === 'subscribe') {
        body = `
              <xml>
                  <ToUserName><![CDATA[${toFromName}]]></ToUserName>
                  <FromUserName><![CDATA[${toUserName}]]></FromUserName>
                  <CreateTime>${createTime}</CreateTime>
                  <MsgType><![CDATA[text]]></MsgType>
                  <Content><![CDATA[欢迎关注公众号，下面请开始你的表演！🧐]]></Content>
              </xml>
          `;
      } else if (msgType === 'text') {
        const { reply_msg } = replyResult;
        body = `
            <xml>
                <ToUserName><![CDATA[${toFromName}]]></ToUserName>
                <FromUserName><![CDATA[${toUserName}]]></FromUserName>
                <CreateTime>${createTime}</CreateTime>
                <MsgType><![CDATA[text]]></MsgType>
                <Content><![CDATA[${reply_msg}]]></Content>
                <MediaId><![CDATA[media_id]]></MediaId>
            </xml>
        `;
      } else if (msgType === 'event' && event === 'unsubscribe') {
        this.ctx.logger.info(`微信号为：“${toFromName}”的用户取消订阅！`);
      }
      ctx.body = body;
    } catch (e) {
      console.log(e);
    }
  }
}

module.exports = BasicMessageController;
